import axios from 'axios';
import fs from 'fs';
import FormData from 'form-data';
import dotenv from 'dotenv';
import { log } from '../utils/utils.js';
dotenv.config();
const CINEMA_CODE = process.env.CINEMA_CODE || 'Master';
const CINEMA_ACC_ID = Number(process.env.CINEMA_ACC_ID) || 0;
const CINEMA_ID = Number(process.env.CINEMA_ID) || 0;
const PID_KEY =
  process.env.PID_KEY ||
  process.env.CLIENT_NAME + '_' + process.pid + '_' + Date.now();

const requestInst = axios.create({
  baseURL: process.env.BASE_URL,
  timeout: 15000,
  headers: { Authorization: process.env.AUTHORIZATION },
});

// 添加响应拦截器
requestInst.interceptors.response.use(
  function (response) {
    const { status, data } = response;
    if (status !== 200) {
      return Promise.reject(new Error('网络请求失败: ' + status));
    }
    if (data.code !== 200) {
        console.error(data);
      return Promise.reject(new Error(`${data.msg}[${data.code}]`));
    }
    return data;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default class Api {
  getPidKey() {
    return PID_KEY;
  }

  // 获取需激活的客户端
  activeCinemaList() {
    return requestInst
      .post('/yuekeyun/activeCinemaList', {
        pidKey: PID_KEY,
      })
      .then((res) => res.data || [])
      .catch(() => {
        log('链接服务器出错!');
        return [];
      });
  }

  // 客户端登录态失效
  authExpire(id) {
    return requestInst.post('/yuekeyun/authExpire', {
      id: Number(id),
    });
  }

  // 更新优惠券数
  updateCouponNum(num) {
    return requestInst.post('/yuekeyun/updateCouponNum', {
      id: CINEMA_ACC_ID,
      num,
    });
  }

  // 更新电子券数
  updateETicketNum(num) {
    return requestInst.post('/yuekeyun/updateETicketNum', {
      id: CINEMA_ACC_ID,
      num,
    });
  }

  // 更新VIP余额
  updateVipBalance(balance, cardNumber, cardName = '', mainCard = 1) {
    return requestInst.post('/yuekeyun/updateVipBalance', {
      id: CINEMA_ACC_ID,
      balance: Number(balance),
      cardNumber: String(cardNumber),
      cardName: String(cardName),
      mainCard,
    });
  }

  // 更新Token
  updateLoginToken(id, token) {
    return requestInst.post('/yuekeyun/updateLoginToken', {
      id: Number(id),
      token,
    });
  }

  // 影院信息
  cinemaInfo(orderId = 0) {
    return requestInst
      .post('/yuekeyun/cinemaInfo', {
        accountId: CINEMA_ACC_ID,
        cinemaId: CINEMA_ID,
        orderId,
      })
      .then((res) => res.data || null);
  }

  // 上线
  online() {
    return requestInst.post('/yuekeyun/online', {
      pidKey: PID_KEY,
      cinemaCode: CINEMA_CODE,
      weight: process.env.CLIENT_WEIGHT || 10,
    });
  }

  // 下线
  offline() {
    return requestInst.post('/yuekeyun/offline', {
      pidKey: PID_KEY,
      cinemaCode: CINEMA_CODE,
    });
  }

  // 获取一个记录
  getOneRecord() {
    return requestInst
      .post('/yuekeyun/getAndLock', {
        pidKey: PID_KEY,
        accountId: CINEMA_ACC_ID,
        cinemaId: CINEMA_ID,
      })
      .then((res) => res.data)
      .catch(() => null);
  }

  // PING保持在线
  ping() {
    return requestInst.post('/yuekeyun/ping', {
      pidKey: PID_KEY,
      cinemaCode: CINEMA_CODE,
    });
  }

  // 获取系统配置
  getSysConfig(key) {
    return requestInst.post('/yuekeyun/systemConfig', {
      key,
    })
    .then((res) => res.data)
    .catch(() => null);
  }

  // 出票
  ticket(data) {
    return requestInst.post('/yuekeyun/ticket', data);
  }

  // 订单回退
  orderRollback(id, msg, canRetry = 0) {
    return requestInst.post('/yuekeyun/orderRollback', {
      id: Number(id),
      msg,
      canRetry,
    });
  }

  // 任务列表
  taskList(id, msg, canRetry = 0) {
    return requestInst.post('/yuekeyun/taskList', {
      id: Number(id),
      msg,
      canRetry,
    });
  }

  // 更新成本
  updateOrderCost(id, settleAmount) {
    return requestInst.post('/yuekeyun/updateOrderCost', {
      id: Number(id),
      settleAmount,
    });
  }

  // 更新场次成本
  updateShowlist(cinemaId, accountId, vipPriceStatus, list) {
    return requestInst.post('/yuekeyun/updateShowlist', {
      accountId: Number(accountId),
      cinemaId: Number(cinemaId),
      vipPriceStatus: Number(vipPriceStatus),
      list,
    });
  }

  // 更新院线信息
  updateCinemasData(id, vipPriceStatus, data) {
    return requestInst.post('/yuekeyun/updateCinemasData', {
      id: Number(id),
      vipPriceStatus: Number(vipPriceStatus),
      data,
    });
  }

  // 上传优惠券列表
  uploadCoupon(couponList, accId, account, plat) {
    if (couponList.length <= 0) {
      return;
    }
    return requestInst.post('/yuekeyun/uploadCouponList', {
      couponList,
      accId: Number(accId),
      account: String(account),
      plat: String(plat),
    });
  }

  // 上传截图
  async uploadScreenshot(file) {
    let formData = new FormData();
    let imgFiles = fs.createReadStream(file);
    formData.append('file', imgFiles);
    let len = await new Promise((resolve, reject) => {
      return formData.getLength((err, length) =>
        err ? reject(err) : resolve(length)
      );
    });
    return await requestInst({
      url: '/yuekeyun/uploadScreenshot',
      method: 'POST',
      headers: {
        ...formData.getHeaders(), // 小心
        'Content-Length': len, // 谨慎
      },
      data: formData,
    })
      .then((res) => res.data.uploadLink || '')
      .catch((e) => {
        console.log('上传图片失败', e);
        return '';
      });
  }

  // 通知后端有会员卡活动
  noticeCardActivity(accountId, cinemaId, cinemaName, account, cardData) {
    return requestInst.post('/yuekeyun/noticeCardActivity', {
      accountId,
      cinemaId,
      cinemaName,
      account,
      cardData,
    });
  }

  // 关闭影院
  closeCinema(id) {
    return requestInst.post('/yuekeyun/closeCinema', {
      id: Number(id),
    });
  }
}
